<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  users
 */

class m_users_actions_block_front_RegistrationAction extends f_core_Action
{    
	public function execute()
	{
        $formProvider = f_form_Provider::getInstance();
        $blockParams = $this->getBlockContext()->getParameters();

        if(!is_null($this->getRequestParameter("activ")))
        {
            $activ = $this->getRequestParameter("activ");
            $valid = $this->getDocumentProvider()->loadDocuments("modules_users/activation")->whereIsEqual("url", $activ)->retrieveFirstDocument();
            if(!is_null($valid))
            {
                $user = $this->getDocumentProvider()->getByModelAndUniqueId("modules_users/user", $valid->getUser());
                $user->setPublicationStatus("PUBLISHED")->save(false);
                $valid->delete();
            }
            else
            {
                $this->addToModel('noLink', true);
            }

            $this->addToModel("active", true);
            return $this->setView('success');
        }

		$formProvider->setDocumentName("users")
		             ->setModuleName("users")
		             ->setFormName("FormRegistration");


		$values = $formProvider->getParams();

		if($formProvider->isSubmitted())
		{
			if($formProvider->isValid())
			{
                $key = m_backoffice_services_BackOfficeService::getKey();
                $user = m_users_documents_User::createNew()
                                    ->setAuthor('Pagizer')
                                    ->setLabel($values['formValues']['login'])
                                    ->setFirstname($values['formValues']['prenom'])
                                    ->setLastname($values['formValues']['nom'])
                                    ->setLogin($values['formValues']['login'])
                                    ->setEmail($values['formValues']['mail'])
                                    ->setPassword(md5($values['formValues']['password'].$key));

                if($blockParams['accountActivation'])
                {
                    $user->setPublicationStatus("DRAFT");
                }

                $user->save(false);

                $docProvider = $this->getDocumentProvider();

                $group = $docProvider->checkDocument($blockParams['group'])
                            ? $docProvider->getByModelAndUniqueId("modules_users/group", $blockParams['group'])
                            : $docProvider->loadDocuments("modules_users/group")->retrieveFirstDocument();
                
				$group->addUser($user)->save();

                $website = $this->getContext("currentWebsite");

                $mailInfos = array("website" => $website, "login" => $user->getLogin(), "password" => $values['formValues']['password']);
                if($blockParams['accountActivation'])
                {
                    $activ = md5($user->getEmail().$key);
                    $link = $this->getContext("currentPage")->getCompleteUrl() . "?activ=" . $activ;
                    $link = array("link" => $link);

                    m_users_documents_Activation::createNew()->setUrl($activ)->setUser($user->getUniqueId())->save(false);
                    $mailInfos = array_merge($mailInfos, $link);
                }

                $mail = f_mail_MailService::getInstance();
                $mail->setSenderName("pagizer")
                     ->setSender("admin@pagizer.org")
                     ->setReceiver($user->getEmail())
                     ->setSubject($this->getLocale("users.form.registrationSubject", null, array('siteName' => $website->getLabel())))
                     ->setContentFromTemplate("users", "registration.html", array("values" => $mailInfos))
                     ->send();

                $blockParams['accountActivation'] ? $this->addToModel("registerActivation", true) : $this->addToModel("register", true);
            }
            else
            {
                $this->addToModel("values", $values['formValues']);
                $this->addToModel("errors", $formProvider->getErrors());
            }
        }
        
        $this->addToModel("blockParams", $blockParams);
		$this->setView('success');
	}	
	
	public function validate()
	{
		return true;
	}
	
	public function errorHandler()
	{
		$this->setView('error');
	}
}